package com.tvunetworks.center.user.resolver;

import com.tvunetworks.center.common.constant.LocalConstant;
import com.tvunetworks.center.common.model.LoginUser;
import com.tvunetworks.center.user.annotation.Logined;
import com.tvunetworks.center.user.util.GetSessionUtils;
import com.tvunetworks.center.user.util.RedisUtil;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
/**
 * @program: tvucc-aggregator
 * @description:
 * @author lebronchen
 * @create: 2021-03-31 13:00
 **/

public class LoginedArgumentResolver implements HandlerMethodArgumentResolver {



    private RedisUtil redisUtil;

    public LoginedArgumentResolver(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        // 如果该参数注解有@Logined
        if (parameter.getParameterAnnotation(Logined.class) != null
                && parameter.getParameterType() == LoginUser.class) {
            // 支持解析该参数
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
        String accessToken = GetSessionUtils.getToken(request);
      //  String accessToken = request.getHeader(LocalConstant.ACCESS_TOKEN_KEY);
        LoginUser loginUser = (LoginUser) redisUtil.get(LocalConstant.REDIS_LOGIN_USER_KEY + accessToken);
        return loginUser;
    }

}
